import axios from "axios";
import router from "@/router/index.js";

import { BASE_URL, REQUEST_TOKEN_KEY } from './config';

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: BASE_URL,
  timeout: 10000, // 请求超时时间
  withCredentials: true, // 允许携带 cookie
  headers: {
    "Content-Type": "application/json",
    "Tzdsj-Origin": "pc",
  },
});

// 异常拦截处理器
function errorHandler(error) {
  if (error.response) {
    const { data = {}, status, statusText } = error.response;

    // 403 无权限
    if (status === 403) {
      showNotify({
        type: "danger",
        message: (data && data.message) || statusText,
      });
    }

    // 401 未登录/未授权
    if (status === 401 && data.result && data.result.isLogin) {
      showNotify({
        type: "danger",
        message: "Authorization verification failed",
      });
      // 如果你需要直接跳转登录页面
      // location.replace(loginRoutePath)
    }
  }
  return Promise.reject(error);
}

// 请求拦截器
function requestHandler(config = {}) {
  const savedToken = localStorage.getItem("token");

  // 有token,让每个请求携带自定义 token
  if (savedToken) {
    config.headers[REQUEST_TOKEN_KEY] = savedToken;
  }

  //  判断是不是 get 请求
  if (config.method == "get") {
    config.params = {
      ...config.data,
      _t: Math.floor(new Date().getTime() / 1000),
    };
  }

  return config;
}

// Add a request interceptor
request.interceptors.request.use(requestHandler, errorHandler);

// 响应拦截器
function responseHandler(response) {
  if (response.data.code === 600) {
    console.log("token过期");
    localStorage.removeItem("token");
    router.push("/");
  }

  return response.data;
}

// Add a response interceptor
request.interceptors.response.use(responseHandler, errorHandler);

export function get(config = {}) {
  return request(Object.assign(config, { method: "GET" }));
}

export function post(config = {}) {
  return request(Object.assign(config, { method: "POST" }));
}

export default request;
